const {
	wxMenu,
} = require('../../../config/server');

exports.gateway = async ctx => {
	const query = ctx.query;
	ctx.set('Content-Type', 'text/plain');
	if (query.echostr || query.nonce) {
		ctx.body = query.echostr || query.nonce;
	} else {
		ctx.status = 403;
		ctx.body = 'token verify incorrect';
	}
};

exports.redirect = async ctx => {
	const { query } = ctx;
	const path = query.path ? decodeURIComponent(query.path) : '/';
	const redirectUrl = ctx.app.wechatOauth.getAuthorizeURL(`${ctx.protocol}://${ctx.host}${path}`);
	ctx.redirect(redirectUrl);
};

exports.test = async ctx => {
	const { query } = ctx;
	const info = await ctx.app.wechatOauth.getAccessToken(query.code);
	ctx.set('Content-Type', 'text/plain');
	ctx.body = `openid => ${info.data.openid}, token => ${info.data.access_token}`;
};

exports.createMenu = async ctx => {
	const menu = wxMenu;

	try {
		const res = await ctx.app.wechatApi.createMenu(menu);
		ctx.set('Content-Type', 'text/plain');
		ctx.body = JSON.stringify(res);
	} catch (err) {
		ctx.logger.error(err);
		console.log(`${err.name} => ${err.code}`);
		ctx.set('Content-Type', 'text/plain');
		ctx.body = JSON.stringify(err);
	}
};
